package com.bdqn.membersystem.controller;

import com.alibaba.fastjson.JSONObject;
import com.bdqn.membersystem.bo.PageBO;
import com.bdqn.membersystem.pojo.AuUser;
import com.bdqn.membersystem.service.AuUserService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：姚岳城
 * @description:后台管理/用户管理
 * 日期：2020/4/21 11:02
 */
@RestController
@Log4j
@RequestMapping(value = "/backend")
public class BackendController {

    @Autowired
    private AuUserService auUserService;

    /**
     * 修改密码
     * @return
     */
    @PostMapping(value = "/modifyPwd.html")
    @ResponseBody
    public Object modifyPwd(HttpSession session,@RequestParam("userJson") String userJson) {
        log.info("userJson"+userJson);
        AuUser user = (AuUser) session.getAttribute("user");
        AuUser auUser = JSONObject.parseObject(userJson, AuUser.class);
        log.info("值"+auUser);

        auUser.setLoginCode(user.getLoginCode());
        if (userJson == null || userJson.equals("")) {
            log.info("对不起，没有任何数据需要处理！请重试。");
            return "nodata";
        } else if (auUserService.selectAuUserByPassword(auUser) == null) {
            log.info("原密码不正确！请重试。");
            return "oldpwdwrong";
        } else if (auUserService.selectAuUserByPassword(auUser) != null) {
            auUser.setId(user.getId());
            auUser.setPassword(auUser.getPassword2());

            Integer updatemodifyPwd = auUserService.updateModifyPwd(auUser);

            if (updatemodifyPwd == null) {
                log.info("修改密码失败！请重试。");
                return "failed";
            } else {
                log.info("修改密码成功 ，下次登录记得使用新密码哦。");
                return "success";
            }
        }else {
            log.info("修改密码成功 ，下次登录记得使用新密码哦。");
            return "success";
        }
    }

    /**
     * 后台管理/用户管理
     * @param session
     * @return
     */
    @RequestMapping(value = "/userlist.html")
    public ModelAndView userList(HttpSession session, ModelMap modelMap){
        AuUser user = (AuUser) session.getAttribute("user");
        String mList = (String) session.getAttribute("mList");
        //查询用户列表
        modelMap.addAttribute("mList",mList);

        return new ModelAndView("/backend/userlist",modelMap);
    }
    protected List<PageBO> getUserList(String loginCode){
        List<PageBO> pageBOList=new ArrayList<>();
        List<AuUser> userList = auUserService.selectAuUser(loginCode);
        if (userList != null) {
            for (AuUser auUser : userList) {
                PageBO page=new PageBO();
                page.setItems(auUser);
                pageBOList.add(page);
            }
        }
        return pageBOList;
    }

}